//
//  ProductListView.swift
//  casdon_swiftUI
//
//  Created by casdon on 2025/5/9.
//
import SwiftUI
import SwiftUIPager
import SDWebImageSwiftUI

struct ProductCategoryView: View {

    @Binding var allowInnerScroll: Bool
//    @Binding var categories: [Level1Item]
    @ObservedObject var viewModel: AddDeviceViewModel
    
    var selectedCategory: Level1Item? {
        viewModel.productList.first(where: { $0.id == viewModel.selectedCategoryID })
       }
    
    init(allow: Binding<Bool>, viewModel: AddDeviceViewModel) {
        _allowInnerScroll = allow
        self.viewModel = viewModel
    }
    
    var body: some View {
        GeometryReader { geometry in
            HStack(spacing: 0) {
                // 左侧分类，占 20%
                List(viewModel.productList) { category in
                    HStack {
                        (category.id == viewModel.selectedCategoryID ? AppColors.Brand6 : Color.clear)
                            .frame(width: 3, height: 14)
                        Text(category.name)
                            .lineLimit(1)
                            .font(.system(size: 14))
                            .fontWeight(category.id == viewModel.selectedCategoryID ? .bold : .regular)
                            .foregroundColor(category.id == viewModel.selectedCategoryID ? AppColors.Brand6 : AppColors.Gy2)
                            .padding(.vertical, 8)
                        
                        Spacer()
                    }
                    .listRowSeparator(.hidden)
                    .listRowInsets(EdgeInsets())
                    .contentShape(Rectangle()) // 扩大点击区域
                    .listRowBackground(category.id == viewModel.selectedCategoryID ? AppColors.White : AppColors.Gray1)
                    .onTapGesture {
                        viewModel.selectedCategoryID = category.id
                        self.viewModel.selectedCategoryID = viewModel.selectedCategoryID
                        self.viewModel.getSecondaryCategory()
                    }
                }
                .listStyle(.plain)
                .frame(width: geometry.size.width * 0.2)
                .background(AppColors.Gray1)
                
                // 右侧内容，占 80%
                if let selected = selectedCategory {
                    ScrollViewReader { proxy in
                        ScrollView(.vertical, showsIndicators: false) {
                            VStack(alignment: .leading, spacing: 20) {
                                GeometryReader { scrollGeo in
                                    Color.clear
                                        .preference(key: InnerScrollOffsetKey.self,
                                                    value: scrollGeo.frame(in: .named("inner")).minY)
                                }
                                .frame(height: 0)
                                Color.clear.frame(height: 0).id("top") 
                                Text(selected.name)
                                    .font(.title3)
                                    .bold()
                                    .padding(.top, 8)
                                
                                LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: 3), spacing: 10) {
                                    ForEach(selected.level3List) { item in
                                            ProductItemView(iconURL: item.icon, name: item.name)
                                    }
                                }
                            }
                            .padding(.horizontal)
                        }
                        .id(viewModel.selectedCategoryID) // 强制让 ScrollView 重新构建
                        .disabled(!allowInnerScroll)
                        .frame(width: geometry.size.width * 0.8)
                        .coordinateSpace(name: "inner")
                        .onChange(of: viewModel.selectedCategoryID) { _ in
                            print("CCCCCCCCCCCCCCCCCCCCCCCCC")
                            withAnimation {
                                proxy.scrollTo("top", anchor: .top)
                            }
                        }
                    }
                }
            }
        }
    }
}

struct ProductItemView: View {
    let iconURL: String
    let name: String

    var body: some View {
        VStack {
            if let url = URL(string: iconURL) {
                WebImage(url: url)
                    .resizable()
                    .indicator(.activity)
                    .scaledToFit()
                    .frame(width: 50, height: 50)
            } else {
                Image(systemName: "photo")
                    .resizable()
                    .frame(width: 50, height: 50)
                    .foregroundColor(.gray)
            }

            Text(name)
                .font(.caption)
        }
    }
}




struct InnerScrollOffsetKey: PreferenceKey {
    static var defaultValue: CGFloat = 0
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = nextValue()
    }
}

